<template>
  <div class="page_body">
    <HomeTop :topTitle="topTitle"></HomeTop>

    <div class="page">
      <div class="page_content">
        <div class="page_banner">
          <img class="banner_img" :src="record.image_path" alt="" />
        </div>
        <div class="page_title">
          <div class="page_title_box">
            <div class="title">{{ record.title }}</div>
            <div class="time">
              <img
                class="img_icon"
                src="../../assets/image/time_icon01.png"
                alt=""
              />
              <div>{{ record.start_date }}</div>
            </div>
            <div class="address">
              <img
                class="img_icon"
                src="../../assets/image/address_icon01.png"
                alt=""
              />
              <div>{{ record.address }}</div>
            </div>
          </div>
          <!-- <div>zbiao {{ this.bue }}</div> -->
        </div>

        <div
          class="page_detail signOne"
          v-if="is_signin == 2 && record.in_signin_time == 1"
        >
          <div>
            <div class="sign_box" @click="goSign()">
              <div>
                <div class="sign_time">{{ nowTime }}</div>
                <div class="sign_title">签到</div>
              </div>
            </div>
            <div class="sign_msg">已到可签到时间</div>
          </div>
        </div>
        <div
          class="page_detail signTwo"
          v-if="is_signin == 2 && record.in_signin_time == 2"
        >
          <div>
            <div class="sign_box" @click="goSign()">
              <div>
                <div class="sign_time">{{ nowTime }}</div>
                <div class="sign_title">签到</div>
              </div>
            </div>
            <div class="sign_msg">未到可签到时间</div>
          </div>
        </div>
        <div class="page_detail signThree" v-if="is_signin == 1">
          <div>
            <div class="sign_box">
              <div>
                <div class="sign_imgBox">
                  <img
                    class="sign_img"
                    src="../../assets/image/sign_success.png"
                    alt=""
                  />
                </div>
                <div class="sign_time">{{ nowTime }}</div>
                <div class="sign_title">签到成功</div>
              </div>
            </div>
            <div class="sign_msg">已签到</div>
          </div>
        </div>
      </div>
      <!-- <div style="height: 1.8rem"></div> -->
    </div>
    <div class="page_bottom">
      <van-tabbar route>
        <van-tabbar-item
          replace
          :to="`/enroll/coach/sign?id=${id}`"
          icon="map-marked"
          >签到</van-tabbar-item
        >
        <van-tabbar-item
          replace
          :to="`/enroll/coach/signDetailList?id=${id}`"
          icon="label"
          >签到记录</van-tabbar-item
        >
      </van-tabbar>
    </div>
    <div style="height: 1.25rem"></div>
    <van-dialog
      v-model="show"
      title="提示"
      width="5.6rem"
      :showConfirmButton="false"
    >
      <div class="sign_dialog">
        <div v-if="dialogStatus == 0" style="font-size: 0.3rem; color: #fe6d68">
          签到查询有误
        </div>
        <img
          v-if="dialogStatus == 1"
          class="dialog_img"
          src="../../assets/image/sign_fail.png"
          alt=""
        />

        <div class="sign_fail" v-if="dialogStatus == 1">
          <div class="sign_fail_title">签到失败</div>
          <div>{{ signError_title }}</div>
        </div>
        <div
          v-if="dialogStatus == 0"
          class="sign_botton"
          @click="closeWindow()"
        >
          确认
        </div>
        <div
          v-if="dialogStatus == 1"
          class="sign_botton"
          @click="confirmClose()"
        >
          确认
        </div>
      </div>
    </van-dialog>
  </div>
</template>
  
  <style src="../../assets/css/enroll/coachSign.css" scoped></style>
  
  <script>
// 引入微信JSSDK
import wx from "weixin-js-sdk";
import HomeTop from "@/components/homeTop.vue";
import { TabContainer, TabContainerItem } from "mint-ui";
import { Indicator, Toast } from "mint-ui";
import { Dialog, Tabbar, TabbarItem } from "vant";

export default {
  name: "signIn",
  // inject: ["reload"],
  components: {
    HomeTop,
    [Dialog.Component.name]: Dialog.Component,
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
  },
  data() {
    return {
      topTitle: "教练员签到", // 顶部组件参数设置
      record: {}, //详情信息
      signError_title: "",
      is_signin: "", //是否已签到
      show: false, //提示弹窗展示判断
      nowTime: "", //当前时间
      dialogStatus: "", //1：签到失败
      active: 0,
      id: "", //二维码ID
      wxJSSDKConfig: {}, // 微信JSSDK配置
      realUrl: "",
      lng: 0,
      lat: 0,
      locationAVail: false,
      url: "",
      is_can: "",
      // showbuak: true,
    };
  },
  created() {
    this.id = this.$route.query.id;
    // console.log(this.id);
    // str.substring;
    this.url = this.$route.fullPath.substring(1);
    this.realUrl = this.$store.state.baseUrl + this.url;
    //   this.isComplete()

    this.nowTimes(); //获取时间的方法
    this.eventDetail();
  },
  mounted() {},

  methods: {
    // 获取WXJSSDK配置
    getWXJSSDKConfigFn: function () {
      let that = this;
      let data = {};
      data = {
        url: that.realUrl,
      };

      let url = "/mobile/getjssdkconfig";
      // console.log(that.realUrl);
      return new Promise(function (resolve, reject) {
        that.axios
          .post(url, data)
          .then((response) => {
            if (response.code == 0) {
              that.wxJSSDKConfig = response.signpackage;
              resolve(true);
            } else {
              Toast({
                message: response.msg,
                duration: 3000,
              });
              resolve(false);
            }
          })
          .catch(function (error) {
            reject(error);
          });
      });
    },
    // deleteconfirm() {
    //   this.showbuak = false;
    //   //
    // },
    openmap() {
      let that = this;
      this.getWXJSSDKConfigFn().then((res) => {
        console.log(res);
        if (res) {
          // wx.config({
          //   debug: false, // 开启调试模式,调用的所有 api 的返回值会在客户端 alert 出来，若要查看传入的参数，可以在 pc 端打开，参数信息会通过 log 打出，仅在 pc 端时才会打印。
          //   appId: that.wxJSSDKConfig.appid, // 必填，公众号的唯一标识
          //   timestamp: that.wxJSSDKConfig.time, // 必填，生成签名的时间戳
          //   nonceStr: that.wxJSSDKConfig.password, // 必填，生成签名的随机串
          //   signature: that.wxJSSDKConfig.signature, // 必填，签名
          //   jsApiList: ["getLocation"], // 必填，需要使用的 JS 接口列表
          // });

          wx.ready(function () {
            // iphone && JSON.parse(localStorage.getItem("updatePage")) == 1
            wx.checkJsApi({
              jsApiList: ["getLocation"],
              success: function (res) {
                if (res.checkResult.getLocation == false) {
                  alert("您的设备不支持获取地理位置信息！");
                  return;
                }
              },
              fail: function (err) {
                alert("您的设备不支持！");
              },
            });
            wx.getLocation({
              type: "wgs84",
              success: function (res) {
                console.log(res);
                //签到打卡范围
                // this.lng = res.longitude; //经度
                // this.lat = res.latitude; //维度
                sessionStorage.setItem("lng", res.longitude);
                sessionStorage.setItem("lat", res.latitude);
                console.log(
                  sessionStorage.getItem("lng"),
                  sessionStorage.getItem("lat")
                );
                // // this.gosin();
                // console.log(
                //   sessionStorage.setItem("lng", res.longitude),
                //   sessionStorage.setItem("lat", res.latitude)
                // );
              },
              fail: function (err) {
                console.log("oookoooo");
                // alert("获取定位位置信息失败！");
                window.location.reload();
              },
            });
          });
          wx.error(function (res) {
            if (
              res.errMsg == "config:invalid signature" &&
              res.realAuthUrl[0] != "" &&
              res.realAuthUrl[0] != undefined
            ) {
              that.realUrl = res.realAuthUrl[0];
            }
            // config信息验证失败会执行 error 函数，如签名过期导致验证失败，具体错误信息可以打开 config 的debug模式查看，也可以在返回的 res 参数中查看，对于 SPA 可以在这里更新签名。
          });
        }
      });
    },

    //显示当前时间（年月日时分秒）
    timeFormate(timeStamp) {
      let hh =
        new Date(timeStamp).getHours() < 10
          ? "0" + new Date(timeStamp).getHours()
          : new Date(timeStamp).getHours();
      let mm =
        new Date(timeStamp).getMinutes() < 10
          ? "0" + new Date(timeStamp).getMinutes()
          : new Date(timeStamp).getMinutes();
      // let ss = new Date(timeStamp).getSeconds() < 10 ? "0" + new Date(timeStamp).getSeconds() : new Date(timeStamp).getSeconds();
      this.nowTime = hh + ":" + mm;
    },
    nowTimes() {
      this.timeFormate(new Date());
      setInterval(this.nowTimes, 1000);
      // 清除定时器，解决网页卡顿问题
      clearInterval(this.nowTimes);
      this.nowTimes = null;
    },

    //点击签到判断是否完善信息
    //   isComplete() {
    //     let url = "/mobile/checkUserInfo";
    //     Indicator.open();
    //     this.axios
    //       .post(url)
    //       .then((res) => {
    //         Indicator.close();
    //         if (res.code == 0) {
    //           // 是否完善信息
    //           if (res.is_complete == "2") {
    //             // this.show = false;
    //           } else if (res.is_complete == "1") {
    //             this.show = true;
    //             this.dialogStatus = 2;
    //           }
    //         } else {
    //           Toast({
    //             message: res.msg,
    //             duration: 3000,
    //           });
    //         }
    //       })
    //       .catch(function (error) {
    //         Indicator.close();
    //         console.log(error);
    //       });
    //   },
    //   //前往裁判员完善信息
    //   confirmComplete() {
    //     this.$router.push({
    //       name: "perfectReferees",
    //       query: {
    //         id: this.id,
    //       },
    //     });
    //   },
    //签到失败关闭弹窗
    confirmClose() {
      this.show = false;
    },
    //关闭当前窗口
    closeWindow() {
      var ua = window.navigator.userAgent.toLowerCase();
      if (ua.match(/MicroMessenger/i) == "micromessenger") {
        WeixinJSBridge.call("closeWindow");
      } else {
        window.location.href = "about:blank";
        window.close();
      }
    },
    //签到
    goSign() {
      console.log("00220202222www", sessionStorage.getItem("lng"));
      let url = "/mobile/checkDistance";
      let data = {
        id: this.$route.query.id,
        longitude: sessionStorage.getItem("lng"),
        latitude: sessionStorage.getItem("lat"),
      };
      this.axios.post(url, data).then((res) => {
        console.log(res);
        this.eventDetail();
        if (res.code == 0) {
          // this.is_can = res.is_can;
          if (res.is_can == "1") {
            if (this.is_signin == 2 && this.record.in_signin_time == 1) {
              this.gosins();
            } else if (this.is_signin == 2 && this.record.in_signin_time == 2) {
              Toast({
                message: "未到签到时间",
                duration: 3000,
              });
            }
          } else if (res.is_can == "2") {
            Toast({
              message: "未到签到范围",
              duration: 3000,
            });
          }
        }
      });
    },
    gosins() {
      let id = this.$route.query.id;
      let url = "/mobile/userSignin";
      let data = {
        id: id,
      };
      // Indicator.open();
      this.axios
        .post(url, data)
        .then((res) => {
          if (res.code == 0) {
            Toast({
              message: "签到成功",
              duration: 3000,
            });
            this.eventDetail();
          } else {
            Toast({
              message: res.msg,
              duration: 3000,
            });
          }
          // if (res.code == 2) {
          //   this.dialogStatus = 1;
          //   this.show = true;
          // }
        })
        .catch(function (error) {
          Indicator.close();
          console.log(error);
        });
    },
    //比赛名称以及详情
    eventDetail() {
      let id = this.$route.query.id;
      let url = "/mobile/signinEventDetail";
      let data = {
        id: id,
      };
      // Indicator.open();
      this.axios
        .post(url, data)
        .then((res) => {
          if (res.code == 0) {
            this.record = res.record;
            this.is_signin = res.is_signin;
            this.openmap();
          }
          if (res.code == 1) {
            this.signError_title = res.msg;
            this.dialogStatus = 0;
            this.show = true;
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  },

  beforeDestroy() {
    // //销毁定时器
    // clearInterval(this.nowTimes);
    // this.nowTimes = null;
  },
};
</script>
<style scoped>
.ps {
  text-align: center;
  line-height: 0.4rem;
  font-size: 0.32rem;
}
.singtwo {
  color: #f63051;
}
.singone {
  color: #4aca6d;
}
</style>
  